package team.knowers.qzh.qzhserver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import team.knowers.qzh.qzhserver.dao.entity.CourseEvaluationDO;
import team.knowers.qzh.qzhserver.dao.entity.UserDO;
import team.knowers.qzh.qzhserver.dao.mapper.CourseEvaluationMapper;
import team.knowers.qzh.qzhserver.dto.req.AddEvaluationReqDTO;
import team.knowers.qzh.qzhserver.dto.req.EvaluationPageReqDTO;
import team.knowers.qzh.qzhserver.dto.resp.EvaluationPageRespDTO;
import team.knowers.qzh.qzhserver.service.CourseEvaluationService;
import team.knowers.qzh.qzhserver.service.UserService;

/**
 * 课程评价服务实现层
 *
 * @author xtg
 */
@Service
@RequiredArgsConstructor
public class CourseEvaluationServiceImpl extends ServiceImpl<CourseEvaluationMapper, CourseEvaluationDO> implements CourseEvaluationService {
    private final UserService userService;

    @Override
    public int addEvaluation(AddEvaluationReqDTO req) {
        CourseEvaluationDO bean = BeanUtil.toBean(req, CourseEvaluationDO.class);
        UserDO userDO = userService.getBaseMapper().selectOne(Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, req.getUsername()));
        bean.setNickname(userDO.getNickname());
        bean.setAvatar(userDO.getAvatar());
        return baseMapper.insert(bean);
    }

    @Override
    public IPage<EvaluationPageRespDTO> pageEvaluation(EvaluationPageReqDTO requestParam) {
        LambdaQueryWrapper<CourseEvaluationDO> queryWrapper = Wrappers.lambdaQuery(CourseEvaluationDO.class).eq(CourseEvaluationDO::getCourseId, requestParam.getCourseId())
                .eq(CourseEvaluationDO::getDelFlag, 0)
                .orderByDesc(CourseEvaluationDO::getCreateTime);
        IPage<CourseEvaluationDO> resultPage = baseMapper.selectPage(requestParam, queryWrapper);
        return resultPage.convert(each -> BeanUtil.toBean(each, EvaluationPageRespDTO.class));
    }

}
